package service

import (
	"cat_mouse/core/dao"
	m "cat_mouse/core/model"
	"cat_mouse/infra/utils/log"
	"sync"
	"time"
)

type ITokenService interface {
	ValidToken(token string) (string, bool)
	ClearToken()
}

type TokenService struct {
	tokenDao *dao.TokenDao
}

func (t *TokenService) ClearToken() {
	err := t.tokenDao.DelExpiredToken()
	if err != nil {
		log.Logger.Error(err)
	}
}

func (t *TokenService) ValidToken(token string) (userId string, result bool) {
	tokenIns := m.Token{}
	err := t.tokenDao.GetOneByCondition(&tokenIns, map[string]interface{}{"token": token})
	if err != nil {
		log.Logger.Error(err)
		result = false
		return
	}
	if time.Now().After(tokenIns.ExpireAt.Time) {
		log.Logger.Error("token已过期")
		result = false
		return
	}
	userId = tokenIns.UserId
	return
}

var (
	tokenSvc     *TokenService
	tokenSvcOnce sync.Once
)

func NewTokenService() ITokenService {
	tokenSvcOnce.Do(func() {
		tokenSvc = &TokenService{
			tokenDao: dao.NewTokenDao(),
		}
	})
	return tokenSvc
}
